package com.example.blog.service;

import com.example.blog.dao.TagRepository;
import com.example.blog.exception.NotFoundException;
import com.example.blog.pojo.Tag;
import com.example.blog.pojo.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class TagServiceImpl implements TagService{
    @Autowired
    TagRepository tagRepository;
    @Override
    @Transactional
    public Tag saveTag(Tag Tag) {
        Tag tag = tagRepository.save(Tag);
        return tag;
    }

    @Override
    @Transactional
    public Tag getTag(Long id) {
        Tag Tag = tagRepository.getOne(id);

        return Tag;
    }

    @Override
    public Tag getTagByName(String name) {
        Tag Tag = tagRepository.findTopByName(name);
        return Tag;
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }
    @Transactional
    @Override
    public Tag updateTag(Long id, Tag Tag) {
        Tag Tag1 = tagRepository.getOne(id);
        if(Tag1 == null){
            new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(Tag,Tag1);

        return tagRepository.save(Tag1);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blog.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return tagRepository.findTop(pageable);

    }

    @Override
    public List<Tag> List(String ids) {
        tagRepository.findAllById(convertToList(ids));
        return null;
    }
    private List<Long> convertToList(String ids){
        List<Long>list= new ArrayList<Long>();
            if("".equals(ids)&& ids != null){
                String[] idarray = ids.split(",");
                for(int i =0; i<idarray.length;i++){
                    list.add(new Long(idarray[i]));
            }
        }
            return list;
    }
    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }
}
